<template>
    <div class="chat-box">
        <!-- <div class="chat-box_record">
            <h1>ChatGPT</h1>
            <button @click="clearMessages">清除消息</button>
        </div> -->
        <div class="chat-sidbar-container">
            <el-button style="width:100%;" type="primary" plain :icon="ChatLineRound" @click="createNewChat">
                开启新的对话
            </el-button>
            <div style="margin-top:10px;"></div>
            <div class="chat-sidbar-container_row" v-for="(item,index) in histList" @click="openHistMessage(index)"><el-text class="mx-1">{{ item.text }}</el-text></div>
        </div>
        <div class="chat-container">
            <div class="messages" ref="listContainer">
                <div class="messages-welcome" v-if="msgWelcomeShow">

                    欢迎使用raymondGPT

                </div>
                <div style="overflow: hidden;" v-else>
                    <div :id="'chatviewlist_'+index" v-for="(item,index) in messagesList">

                        <!-- 系统 -->
                        <div class="message-content-gpt" :class="{ 'gpt-message': item.from == 'gpt' }" v-if="item.from == 'gpt'">
                            <div>
                                <svg width="40" height="40" xmlns="http://www.w3.org/2000/svg">
                                    <rect x="0" y="0" width="40" height="40" rx="40" ry="40" fill="#CCCCCC" />
                                    <text x="7" y="25" :font-size="13" fill="#ffffff">GPT</text>
                                </svg>
                            </div>
                            <div class="message-content-gpt_message">
                                <div>{{ item.text }}</div>
                                <!-- 加载动画 -->
                                <svg width="30" height="30" viewBox="0 0 15 24" v-if="messagesList.length-1 == index && addMesageLoading">
                                    <circle cx="12" cy="12" r="6" fill="#2ecc71">
                                        <animate attributeName="r" values="3;6;3" dur="1.5s" repeatCount="indefinite" />
                                        <animate attributeName="opacity" values="1;0.3;1" dur="1.5s" repeatCount="indefinite" />
                                    </circle>
                                </svg>
                                <!-- <div style="margin-top: 10px;">
                                    <el-icon><CopyDocument /></el-icon>
                                    <el-icon><Refresh /></el-icon>
                                </div> -->
                            </div>
                        </div>

                        <!-- 用户 -->
                        <div class="message-content-user" :class="{ 'user-message': item.from == 'user' }" v-else-if="item.from == 'user'">
                            <!-- 加载动画 -->
                            <svg width="30" height="30" viewBox="0 0 15 24" v-if="messagesList.length-1 == index && addMesageLoading">
                                <circle cx="12" cy="12" r="6" fill="#2ecc71">
                                    <animate attributeName="r" values="3;6;3" dur="1.5s" repeatCount="indefinite" />
                                    <animate attributeName="opacity" values="1;0.3;1" dur="1.5s" repeatCount="indefinite" />
                                </circle>
                            </svg>

                            <div class="message-content-user_message">{{ item.text }}</div>
                            <div>
                                <svg width="40" height="40" xmlns="http://www.w3.org/2000/svg">
                                    <rect x="0" y="0" width="40" height="40" rx="40" ry="40" fill="#007BFF" />
                                    <text x="7" y="25" :font-size="13" fill="#ffffff">user</text>
                                </svg>
                            </div>
                        </div>

                    </div>
                </div>
            </div>
            <div class="message-input">
                <!-- 回到底部 -->
                <div class="back-bottom" v-if="backBottom" @click="backBottomClick">
                    <el-icon><ArrowDownBold /></el-icon>
                </div>
                <div class="message-input_func"></div>
                <div>
                    <!-- 显示上传的图片信息 -->
                    <div class="message-input_image" v-if="imageList">
                        <img :src="imgsrc" alt="图片" v-for="(imgsrc, index) in imageList" :key="index" />
                    </div>
                    <div style="width:100%;height:65px;">
                        <input ref="inputRef" type="textarea" v-model="newMessage" placeholder="发消息`输入@或/选择技能" />
                        <!-- <textarea></textarea> -->
                    </div>
                </div>
                <div style="display: flex;justify-content:space-between;align-items: end;">
                    <div>
                        <el-button plain round :icon="MagicStick" size="small" @click="textPolishing">帮我润色</el-button>
                    </div>
                    <!-- <button :disabled="newMessage.length==0" @click="sendMessage">发送</button> -->
                    <div :class="['message-input_send',newMessage==''?'message-input_send-disabled':'message-input_send-active']" @click="sendMessage">
                        <el-icon><TopRight /></el-icon>
                    </div>
                </div>
            </div>

        </div>
    </div>
</template>

<script setup lang="ts">

import { ref, onMounted,nextTick } from "vue";
import { request } from '../../utils';
// import config from '../../mp.config.js'
import { ArrowDownBold,TopRight,MagicStick,ChatLineRound,Refresh,CopyDocument } from '@element-plus/icons-vue'



const histList=ref([
    {id: 1,text: '历史对话1'},
    {id: 2,text: '历史对话2'},
])
// 明确指定 ref 的类型为 HTMLDivElement
const listContainer=ref<HTMLDivElement | null>(null);
const msgWelcomeShow=ref(false)
const messagesList = ref([
    { id: 1,from:'gpt', text: '你好,我是ChatGPT,你有什么问题想问我吗?' },
    { id: 2,from:'user', text: '你叫什么名字？' },
    { id: 3,from:'gpt', text: '我是ChatGPT,一个由OpenAI开发的聊天机器人。' },
    { id: 4,from:'user', text: '4' },
    { id: 5,from:'gpt', text: '5' },
    { id: 6,from:'user', text: '6' },
    { id: 7,from:'gpt', text: '7' },
    { id: 8,from:'user', text: '8' },
    { id: 9,from:'gpt', text: '9' }
]);

const backBottom=ref(false)
const imageList=ref([
    // 'https://www.baidu.com/img/flexible/logo/pc/result@2.png',
])
// 明确指定 ref 的类型为 HTMLInputElement
const inputRef = ref<HTMLInputElement | null>(null);
const newMessage = ref('');
const addMesageLoading = ref(false);




onMounted(async () => {
    let list=[
        {id: Date.now(),from:'user',text: 'sss',},
        {id: Date.now(),from:'user',text: 'sss',},
        {id: Date.now(),from:'user',text: 'sss',},
        {id: Date.now(),from:'user',text: 'sss',}
    ]
    messagesList.value=messagesList.value.concat(list);
    await nextTick(() => {
        if(listContainer.value){
            listContainer.value.scrollTop = listContainer.value.scrollHeight;
        }
    });
    if (listContainer.value) {
        // 在组件挂载时添加滚动事件监听器到指定元素
        listContainer.value.addEventListener('scroll', handleScroll);
    }

});

/* const clearMessages = () => {

} */

// 创建新聊天
const createNewChat = () => {
    messagesList.value=[];
    msgWelcomeShow.value=true;
};
// 定义一个函数，用于打开历史消息
const openHistMessage = (index) => {
    messagesList.value=[
        {id: Date.now(),from:'user',text: 'sss1',},
        {id: Date.now(),from:'user',text: 'sss2',},
        {id: Date.now(),from:'user',text: 'sss3',},
        {id: Date.now(),from:'user',text: 'sss4',}
    ];
    msgWelcomeShow.value=false;
};

// 处理滚动事件
const handleScroll = () => {
    if (listContainer.value) {
        /* // 获取元素滚动的垂直距离
        const scrollTop = listContainer.value.scrollTop;
        console.log('元素滚动距离:', scrollTop);
        if( scrollTop>0 && scrollTop<listContainer.value.scrollHeight){
            // 滚动距离大于0且小于元素总高度
            backBottom.value=true;
        }else{
            backBottom.value=false;
        } */
    }
};

// 返回底部
const backBottomClick = () => {
    if(listContainer.value){
        listContainer.value.scrollTop = listContainer.value.scrollHeight;
    }
}

// 文本润色
const textPolishing = () => {
    request({url:"http://127.0.0.1:8000/items",method:'POST',data:{text:newMessage.value}}).then(res => {
        if(res.code==0){
            addMesageLoading.value=false;
        }
    }).catch(err => {
        console.log(err)
    })
}

//发送消息
const sendMessage = async () => {

    if(newMessage.value == ''){
        return
    }

    if(msgWelcomeShow.value){
        msgWelcomeShow.value=false;
    }
    addMesageLoading.value=true;
    messagesList.value.push({
        id: Date.now(),
        from:'user',
        text: newMessage.value,
    });
    newMessage.value = '';
    inputRef.value?.focus();

    await nextTick(()=>{
        setTimeout(() => {
            //跳转到消息的最新的开始位置
            // document.querySelector('#chatviewlist_'+(messagesList.value.length-1)).scrollIntoView();

            if(listContainer.value){
                listContainer.value.scrollTop = listContainer.value.scrollHeight;
            }

            setTimeout(() => {
                addMesageLoading.value=false;
            },1000);

            /* request({url:"http://127.0.0.1:8000/items",method:'POST',data:{text:newMessage.value}}).then(res => {
                if(res.code==0){
                    addMesageLoading.value=false;
                }
            }).catch(err => {
                console.log(err)
            }) */

        },0);
    })

}



</script>

<style scoped>
.chat-box {
    display: flex;
    width:80%;
    /* height: 100vh; */
    /* background-color: #f0f0f0; */
}

.chat-box_record {
    display: flex;
    width: 30%;
    height: 100vh;
    margin: auto;
    margin-bottom: 20px;
}
.chat-sidbar-container{
    width:280px;
    background-color: #F6F7FB;
    padding:10px;
}
.chat-sidbar-container_row{
    padding:5px 0;
    cursor: pointer;
}
.chat-container {
    /* border: 1px solid #ccc; */
    border-radius: 5px;
    /* padding: 10px; */
    width: 100%;
    height:100%;
    margin: auto;
    display: flex;
    flex-direction:column;
}

.messages {
    flex:1;
    overflow-y: auto;
    padding: 15px 15px;
    border-radius: 5px;
}
.messages-welcome{
    width:100%;
    height:100%;
    text-align: center;
}
.message-content-gpt,.message-content-user{
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    width:100%;
}
.message-content-user{
    float:right;
}
.message-content-gpt_message,.message-content-user_message{
    border-radius: 10px;
    padding:12px 15px;
    margin:0 10px;
}
.message-content-gpt_message{
    /* background-color: #f0f0f0; */
}
.message-content-user_message{
    background-color: #F6F7FB;
    margin:0 10px 0 5px;
}
.gpt-message {
    justify-content: flex-start;
}

.user-message {
    justify-content: flex-end;
}
.message {
    padding: 10px;
    /* border-bottom: 1px solid #ccc; */
}

input {
    flex: 1;
    padding: 10px;
    border-radius: 5px;
    border:none;
}
/* input 获得焦点时的样式 */
input:focus {
    outline: none;
    border:none;
    /* border: 2px solid yellow;
    box-shadow: 0 0 5px yellow; */
}

/* button {
    padding: 8px 10px;
    margin-left:10px;
    background-color: #007bff;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    width:80px;
}

button:hover,
button:active {
    background-color: #0056b3;
} */

.message-input{
    width:99%;
    height: 150px;
    margin:0 auto;
    padding:5px 10px;
    border:1px solid #ddd;
    border-radius: 10px;
    position: relative;
    .back-bottom{
        width: 40px;
        height:40px;
        box-shadow: 0 0 5px #ddd;
        border-radius: 50px;
        position: absolute;
        top:-60px;
        left:calc(50% - 20px);
        cursor: pointer;
        font-size: 18px;
        color:#0056b3;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .message-input_func{
        height:30px;
    }
    .message-input_image{
        min-height:0px;
        max-height: 50px;
        img{
            height:40px;
        }
    }
    .message-input_send{
        width:40px;
        height:40px;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #B2C6D8;
        border-radius: 50px;
        font-size: 23px;
        font-weight: 550;
        color:#fff;
        cursor: pointer;
    }
    .message-input_send-active{
        background-color: #007bff;
    }
    .message-input_send-disabled{
        background-color: #D6DEE8;
        cursor: not-allowed;
    }
}


</style>